package routefinder;

/**
 * A link which represents a non-negative distance and a target city 
 */
public class Link implements Comparable<Link> {


    /**
     * The linked city
     */
    private City city;
    /**
     * The distance of this link
     */
    private int distance;

    public Link(City city, int distance) {
        if (city == null) {
            throw new NullPointerException("City cannot be null.");
        }
        if (distance < 0) {
            throw new IllegalArgumentException("Distance between two cities cannot be negative.");
        }

        this.city = city;
        this.distance = distance;
    }

    public City getCity() {
        return city;
    }

    public int getDistance() {
        return distance;
    }

    public int compareTo(Link o) {
        int result = distance - o.distance;
        if (result == 0) {
            result = city.getName().compareTo(o.getCity().getName());
        }
        return result;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((city == null) ? 0 : city.hashCode());
        result = prime * result + distance;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Link other = (Link) obj;
        if (city == null) {
            if (other.city != null) {
                return false;
            }
        } else if (!city.equals(other.city)) {
            return false;
        }
        if (distance != other.distance) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return city.getName() + ": " + distance;
    }
}
